package system

import (
	"k8s-admin/global"
	"k8s-admin/models"
	"k8s-admin/utils"
)

type InterfaceUsers interface {
	Login(username, password string) (*models.RespUser, error)
	GetUserFromUserName(username string) (*models.User, error)
}

type userInfo struct{}

func NewUserInterface() InterfaceUsers {
	return &userInfo{}
}

func (r *userInfo) Login(username, password string) (*models.RespUser, error) {
	var user models.User
	if err := global.GORM.Where("username=? and password=?", username, password).First(&user).Error; err != nil {
		return nil, err
	} else {
		token, err := utils.CreateToken(user.UID, user.Username)
		if err != nil {
			return nil, err
		} else {
			return &models.RespUser{

				UID:       user.UID,
				Username:  user.Username,
				Avatar:    user.Avatar,
				Status:    user.Status,
				CreatedAt: user.CreatedAt,
				UpdatedAt: user.UpdatedAt,
				Email:     user.Email,
				Phone:     user.Phone,
				Token:     token,
			}, nil
		}
	}
}
func (r *userInfo) GetUserFromUserName(username string) (*models.User, error) {
	var user models.User
	err := global.GORM.Where("username=?", username).First(&user).Error
	if err != nil {
		return nil, err
	} else {
		return &user, nil
	}
}
